package com.ruiysoft.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruiysoft.crm.mapper.BizBatchClientRecordMapper;
import com.ruiysoft.crm.mapper.BizClientMapper;
import com.ruiysoft.crm.model.entity.BizBatchClientRecord;
import com.ruiysoft.crm.model.entity.BizClient;
import com.ruiysoft.crm.model.entity.SysDict;
import com.ruiysoft.crm.model.entity.SysUser;
import com.ruiysoft.crm.model.vo.BizClientVo;
import com.ruiysoft.crm.service.BizClientService;
import com.ruiysoft.crm.service.SysDictService;
import com.ruiysoft.crm.util.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * @author fanyl
 */
@Service
public class BizClientServiceImpl extends ServiceImpl<BizClientMapper, BizClient> implements BizClientService {
    @Autowired
    private SysDictService sysDictService;

    private final BizClientMapper bizClientMapper;
    private final BizBatchClientRecordMapper bizBatchClientRecordMapper;

    public BizClientServiceImpl(BizClientMapper bizClientMapper, BizBatchClientRecordMapper bizBatchClientRecordMapper) {
        this.bizClientMapper = bizClientMapper;
        this.bizBatchClientRecordMapper = bizBatchClientRecordMapper;
    }

    @Override
    public IPage queryClientInfo(IPage page, Map<String, Object> params) {
        params.remove("page");
        params.remove("pageSize");
        params.remove("isAsc");

        String chudy = (String) params.get("chudy");
        String allocation = (String) params.get("allocation");//是否已分配
        String callFlag = (String) params.get("callFlag");//是否已拨打电话
        if (callFlag != null) {
            params.remove("callFlag");
            if ("1".equals(callFlag)) { //已分配
                params.put("callFlag", " log.`callTime` IS NOT NULL");
            }
            if ("0".equals(callFlag)) { //已分配
                params.put("callFlag", " log.`callTime` IS NULL");
            }
        }

        if (allocation != null) {
            params.remove("allocation");
            if ("1".equals(allocation)) { //已分配
                params.put("allocation", " client.user_name is not null");
            }
            if ("0".equals(allocation)) { //已分配
                params.put("allocation", " client.user_name is null");
            }
        }
        if ("1".equals(chudy)) {
            params.remove("client.user_id");
        }

        params.remove("chudy");
        params.remove("userId");
        params.remove("yewyId");

        List<SysDict> list = sysDictService.list(new QueryWrapper<SysDict>().eq("type", "isShowMobile"));
        SysDict sysDict = null;
        if(list != null && list.size() > 0)
            sysDict = list.get(0);

        List<BizClient> result = bizClientMapper.queryClientAndCarInfo(page, params);

        SysDict finalSysDict = sysDict;
        result.forEach(bizClient -> {
            if (StringUtils.hasText(bizClient.getIdNo())) {
                // 身份证号
//                bizClient.setIdNo(bizClient.getIdNo().replaceAll("(\\d{4})\\d{10}(\\w{4})", "$1*****$2"));
            }

            if (StringUtils.hasText(bizClient.getMobilePhone())) {
                // 电话1
                if(finalSysDict.getValue().equals("0"))
                    bizClient.setMobilePhone(bizClient.getMobilePhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
            }

            if (StringUtils.hasText(bizClient.getStandbyMobile())) {
                // 电话2
                if(finalSysDict.getValue().equals("0"))
                    bizClient.setStandbyMobile(bizClient.getStandbyMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
            }
        });

        Collections.sort(result, new Comparator<BizClient>() {
            @Override
            public int compare(BizClient o1, BizClient o2) {
                if(o1 != null && o1.getModificationDate() != null && o2 != null && o2.getModificationDate() != null)
                    return o1.getModificationDate().isAfter(o2.getModificationDate()) ? 1 : 0; //降序1

                return 0;
            }
        });

        return page.setRecords(result);
    }

    @Override
    public BizClient getClientById(int id) {
        return bizClientMapper.getClientById(id);
    }

    @Override
    public Object recv_center(int i) {
        return null;
    }

    @Override
    public boolean revokeAllotUser(BizBatchClientRecord record) {
        try {
            String clientIds = record.getClientIds();
            if (StringUtils.isEmpty(clientIds)) {
                return false;
            }
            bizClientMapper.revokeAllotUser(clientIds);
            record.setUserId(null);
            record.setBatchType("import");
            record.setUserName(null);
            bizBatchClientRecordMapper.deleteById(record.getId());
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public Object allocationByBatchid(String batchid, SysUser userVO) {
        BizBatchClientRecord bbc = bizBatchClientRecordMapper.selectById(batchid);
        bizClientMapper.allocationByBatchid(batchid, userVO.getUserId(), userVO.getRealName(), bbc.getClientIds());
        bbc.setUserId(userVO.getUserId());
        bbc.setBatchType("allot");
        bbc.setUserName(userVO.getRealName());
        bizBatchClientRecordMapper.updateById(bbc);
        return 1;
    }


    @Override
    public List<BizClientVo> queryClients(Map<String, Object> params) {
        return bizClientMapper.queryClients(params);
    }

    @Override
    public List<String> getCarNos() {
        return bizClientMapper.getCarNos();
    }

    @Override
    public List<String> getEnterpriseCode() {
        return bizClientMapper.getEnterpriseCode();
    }

    @Override
    public List<BizClient> allocationToUser(Map params) {
        String successValue = params.get("success") + "";
        String chudy = params.get("chudy") + "";
        String allocation = params.get("allocation") + "";//是否已分配
        String callFlag = params.get("callFlag") + "";//是否已拨打电话
        if (callFlag != null) {
            params.remove("callFlag");
            if ("1".equals(callFlag)) { //已分配
                params.put("callFlag", " log.`callTime` IS NOT NULL");
            }
            if ("0".equals(callFlag)) { //已分配
                params.put("callFlag", " log.`callTime` IS NULL");
            }
        }

        if (allocation != null) {
            params.remove("allocation");
            if ("1".equals(allocation)) { //已分配
                params.put("allocation", " client.user_name is not null");
            }
            if ("0".equals(allocation)) { //已分配
                params.put("allocation", " client.user_name is null");
            }
        }
        if ("1".equals(chudy)) {
            params.remove("client.user_id");
        }
        params.remove("chudy");
        if ("-1".equals(successValue) || StringUtils.isEmpty(successValue)) {
            params.put("success", "IFNULL(client.success,'-1') = '-1' ");
        } else {
            params.put("success", "IFNULL(client.success,'') in ('" + successValue + "')");
        }

        params.put("page", 1);
        int record = 0;
        try {
            record = Integer.parseInt(params.get("record") + "");
        } catch (Exception e) {
            record = 0;
        }
        if (record == -1 || record == 0) {
            record = 10000000;
        }

        params.put("limit", record);
        IPage page = new Query<>(params);
        params.remove("record");
        params.remove("page");
        params.remove("limit");
        params.remove("isAsc");

        List<BizClient> result = bizClientMapper.queryClientAndCarInfo(page, params);
        return result;
    }

    @Override
    public List getSuccessCountByUserId(String userId) {
        userId = userId == "" ? null : userId;
        return bizClientMapper.getSuccessCountByUserId(userId);
    }

    @Override
    public IPage rejectList(Page feny) {
        return this.page(feny, new QueryWrapper<BizClient>().eq("success", "reject"));
    }
}